package com.code2roc.jarmanage;

import com.code2roc.jarmanage.socket.SSHWebSocketServer;
import com.code2roc.jarmanage.util.*;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

import javax.websocket.server.ServerContainer;
import java.io.File;
import java.util.logging.*;

public class Application {
    public static void main(String[] args){
        try {
            //jar包运行自动解压资源
            ResourceUtil.initResource();
            //监听日志
            LogListenerUtil.initLogListenter();
            //自动初始化数据库
            DataBaseUtil.initDataBase();
            //检查运行环境
            EnviromentUtil.checkEnvInstall();
            //启动tomcat服务
            // 1.创建一个内嵌的Tomcat
            Tomcat tomcat = new Tomcat();
            // 2.设置Tomcat端口
            tomcat.setPort(ConvertUtil.convert2Int(ConfigUtil.getConfigValue("port")));
            // 3.设置工作目录,tomcat需要使用这个目录进行写一些东西
            final String baseDir = "workspace" + File.separator;
            tomcat.setBaseDir(baseDir);
            tomcat.getHost().setAutoDeploy(false);
            // 4. 设置webapp资源路径
            String webappDirLocation = "webapp" + File.separator;
            StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
            // 5. 设置上下文路径
            ctx.setPath(ConfigUtil.getConfigValue("contextpath"));
            ctx.addLifecycleListener(new Tomcat.FixContextListener());
            ctx.setName("jar-manage");
            ctx.setPrivileged(true);
            //6.日志
            Logger logger = LogUtil.getLogger();
            //7 路由映射
            RouteUtil.initMapping(tomcat, ctx);
            //8.启动
            tomcat.getConnector().setURIEncoding("UTF-8");
            tomcat.getConnector().setProperty("maxConnections","20000");
            tomcat.getConnector().setProperty("maxThreads","500");
            tomcat.getConnector().setProperty("maxHttpHeaderSize","20480000");
            tomcat.getEngine().setJvmRoute("-Xmx" + ConfigUtil.getConfigValue("maxMemory") + "m");
            tomcat.start();
            //9.注册websocket
            ServerContainer wsContainer = (ServerContainer) ctx.getServletContext()
                    .getAttribute(ServerContainer.class.getName());
            try {
                wsContainer.addEndpoint(SSHWebSocketServer.class);
            } catch (Exception e) {
                LogUtil.error(e);
            }
            LogUtil.info("Jar Manage Service Start Success");
            tomcat.getServer().await();
        } catch (Exception e) {
            LogUtil.info("Jar Manage Service Start Fail");
            LogUtil.error(e);
        }

    }


}
